<?php

namespace Admin\Controller;

use Admin\Logic\FoodCateLogic;
use Admin\Common\Category;

class FoodCateController extends CommonController
{
    /**
     * 菜谱分类列表展示
     * @return [type] [description]
     */
    public function index()
    {
        $data = FoodCateLogic::getAll();
        if (!empty($data)) {
            $data = Category::toLevel($data);
        }

        $this->assign(['foodCate'=>$data]);
        $this->display();
    }


    /**
     * 展示修改菜谱页面
     */
    public function edit()
    {
        $id = I('get.id', 0, 'intval');

        if ($id < 1) {
            E('非法操作');
        }

        $cate = D('foodCate')->where(['id' => $id])->find();
        $this->assign('cate', $cate);
        $this->display();

    }

    /**
     * 菜谱分类添加视图
     * @Author   zhouyao
     * @DateTime 2017-11-20
     * @version  [version]
     */
    public function add()
    {
        $data = FoodCateLogic::getAll();

        if (!empty($data)) {
            $data = Category::toLevel($data);
        }

        $this->assign(['cate'=>$data]);
        $this->display();
    }

    /**
     * 处理添加菜谱分类
     * @return [type] [description]
     */
    public function store()
    {
        $param = [
            'cate_name' => I('post.cate_name', null, 'htmlspecialchars'),
            'parent_id' => I('post.parent_id', 0, 'intval'),
            'order_sort' => I('post.order_sort', 1, 'intval'),
            'is_show' => I('post.is_show')=='on'?1:0,
            'created_at' => getDateTime()
        ];

        $insert = FoodCateLogic::create($param);

        if ($insert['code'] == 1) {
            return $this->ajaxError($insert['msg']);
        } else {
            return $this->ajaxSuccess('success');
        }
    }

    /**
     * 修改分类信息处理
     * @return string
     */
    public function update()
    {
        $this->checkPost();

        // 接受数据
        $param = [
            'id' => I('post.id', 0, 'intval'),
            'cate_name' => I('post.cate_name'),
            'order_sort' => empty(I('post.order_sort'))?0:I('post.order_sort'),
            'code' =>  sprintf('%04s', I('post.code')),
            'is_show' => I('post.is_show')=='on'?1:0,
            'update_at' => date('Y-m-d H:i:s')
        ];

        // 执行修改
        $result = FoodCateLogic::update($param);

        if ($result === false) {
            return $this->ajaxError('服务器找不到啦~^_^');
        }

        return $this->ajaxSuccess();



    }


    public function delete()
    {
        $id = I('get.id', 0, 'intval');

        $data = FoodCateLogic::delete($id);

        if (json_decode($data,true)['code'] > 0) {
            return $this->ajaxSuccess();
        } else {
            return $this->ajaxError(json_decode($data,true)['errorMsg']);
        }
    }



}